#include <uart2.h>
#include <fpc1020.h>

#define UART_NAME       "uart2"

// 用于接收消息的信号量
static struct rt_semaphore rx_sem;
static rt_device_t serial;

// 接收数据回调函数
static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{
    /* 串口接收到数据后产生中断，调用此回调函数，然后发送接收信号量 */
    rt_sem_release(&rx_sem);

    return RT_EOK;
}

// 串口线程
static void serial_thread_entry(void *parameter)
{
    char ch;
    while (1)
    {
        /* 从串口读取一个字节的数据，没有读取到则等待接收信号量 */
        while (rt_device_read(serial, -1, &ch, 1) != 1)
        {
            /* 阻塞等待接收信号量，等到信号量后再次读取数据 */
            rt_sem_take(&rx_sem, RT_WAITING_FOREVER);
        }
      
		FPC1020_LOG("%02X ",ch);
		
		switch (fpc1020_rLen)
		{
		case 0: 
			if(ch == FPC1020_DATA_START) fpc1020_rLen++;
		break;
//		case 1: 
//			if(ch == fpc1020_cmd) fpc1020_rLen++;
//			else fpc1020_rLen = 0;
//		break;
		case 7: 
			if(ch == FPC1020_DATA_END) 
			{
				FPC1020_LOG("\n");
				FPC1020_LOG("fpc1020_recv_process\n");
				fpc1020_recv_process();
			}
			fpc1020_rLen = 0;
			
		break;
		default:
			fpc1020_rBuf[fpc1020_rLen] = ch;
			fpc1020_rLen++;
		break;
		}

    }
}

//打开串口
rt_err_t uart2_open(void)
{
    rt_err_t ret = RT_EOK;

    /* 查找系统中的串口设备 */
    serial = rt_device_find(UART_NAME);
    if (!serial)
    {
        rt_kprintf("can't find %s device.\n",UART_NAME);
        return RT_ERROR;
    }

    /* 初始化信号量 */
    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);

    /* 以中断接收及轮询发送模式打开串口设备 */
    rt_device_open(serial, RT_DEVICE_FLAG_INT_RX);

    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(serial, uart_input);

    /* 发送字符串 */
    //rt_device_write(serial, 0, str, (sizeof(str) - 1));

    /* 创建 serial 线程 */
    rt_thread_t thread = rt_thread_create("serial", serial_thread_entry, RT_NULL, 1024, 25, 10);
    
    /* 创建成功则启动线程 */
    if (thread != RT_NULL)
        rt_thread_startup(thread);
    else
        ret = RT_ERROR;

    return ret;
}




//串口写数据
void uart2_write(char *buff,int size)
{
    rt_device_write(serial, 0, buff, size);
}
